
import baseConfig from "@/config/index.config.js"
// const baseUrl = 'http://star-wxapi.test.mxklchina.com/WxAPI'
const request = (url, options)=> {
	return new Promise((resolve,reject)=> {
		uni.request({
			url: baseConfig.baseUrl + url,//接口地址，
			method: options.method, //请求方式
			data: options.data,  //请求参数
			header: {   // 请求头配置
				'Content-Type': options.header, //options.header没传application/json;charset=UTF-8格式
				'Authentication': uni.getStorageSync('loginData').token || '',
				'clientType': 'microSite'
			},
			success(data) {
				const res = data.data
				if(res.code == 0) {
					resolve(res)
				} else {
					reject(res)
				}
			},
			fail(error) {
				reject(error.data)
			}
		})
	})
}
//封装get方法
const get = (url, options = {}) => {
	return request(url, {
		method: 'GET',
		header: 'application/json; charset=UTF-8',
		data: options
	})
}

// 封装post方法
const postJson = (url, options = {}) => {
	return request(url, {
		method: 'POST',
		header: 'application/json; charset=UTF-8',
		data: options
	})
}
//封装post方法  参数格式为x-www-form-urlencoded表单形式
const post = (url, options = {}) => {
	return request(url, {
		method: 'POST',
		header: 'application/x-www-form-urlencoded',
		data: options
	})
}
//封装上传方法
const upload = (url, options = {}) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		uni.uploadFile({
			url: baseConfig.baseUrl + url,
			filePath: options.filePath,
			name: options.name,
			//header中可以添加token值等
			header: {
				'Content-Type': 'application/json; charset=UTF-8',
				'Authentication': uni.getStorageSync('loginData').token || '',
				'clientType': 'microSite'
			},
			formData: options.data || {},
			//监听成功后的操作
			success(data) {
				uni.hideLoading()
				const res = JSON.parse(data.data)
				if (res.code == 0) {
					resolve(res)
				} else {
					checkNetwork(res.retMsg)
					if (msg.indexOf('没有登录') >= 0) { // 未登录
						uni.reLaunch({
							url: '/pages/login/login'
						})
					}
					reject(res)
				}
			},
			//返回失败也同样传入reject()方法
			fail(error) {
				uni.hideLoading()
				checkNetwork()
				reject(error.data)
			}
		})
	})
}
module.exports = {
	get,
	post,
	postJson,
	upload,
}